DMD=dmd
#LD=gcc
DFLAGS=-w -version=Wiki -version=Upload -version=BugTracking -version=USE_ZLIB -L-lz
ifdef DEBUG
  DFLAGS:=$(DFLAGS) -g
else
  DFLAGS:=$(DFLAGS) -O -release -inline -L-O3 -L--strip-all
endif
# リリースフラグ
#-O -release -inline -L-O3 -L--strip-all
# 時間計測
#-profile
PREFIX=	sw
INSTALLDIR=/var/www/$(PREFIX)
#LDFLAGS=-lphobos -lpthread -lm
#For Release
# -O --strip-all
DISTVER=0.0.3+
DISTNAME=stwiki

.PHONY : all release debug clean clean_backup dist distsource install uninstall

all: index.cgi $(patsubst %.svg,%.png,$(wildcard *.svg))

debug:
	@DEBUG=1 MAKELEVEL=0 make

#個別にビルドするより一括してビルドした方が早い罠
index.cgi: $(filter-out sw/commandhelp.d, $(wildcard */*.ddoc */*.d */*/*.d */*/*/*.d)) sw/commandhelp.d
	$(DMD) $(DFLAGS) -of$@ $+

sw/commandhelp.d: $(wildcard sw/*/*commands.d)
	echo module sw.commandhelp\; > $@
	echo string getHelp\(\){ >> $@
	echo return \"\<dl\> >> $@
	grep "//\*\ " $+ | sed -e 's/.*\/\/\*/<dt>/g' -e 's/\]\ /]<\/dt><dd>/g' -e 's/$$/<\/dd>/g' >> $@
	echo \</dl\>\"\;\} >> $@

%.png: %.svg
	inkscape -z -f $< -e $@ -w 16 -h 16

#index.cgi: $(patsubst %.d,%.o,$(wildcard */*.ddoc */*.d */*/*.d */*/*/*.d)) sw/commandhelp.o
#	$(LD) -o index.cgi $+ $(LDFLAGS)

#%.o:%.d
#	$(DMD) $(DFLAGS) -c -of$@ $<

clean: clean_backup
	rm -f *.o */*.o */*/*.o */*/*/*.o */*/*/*/*.o index.cgi sw/commandhelp.d *.png

clean_backup:
	rm -f *~ */*~ */*/*~ */*/*/*~ */*/*/*/*~

dist: clean_backup all
	rm -f $(DISTNAME)-$(DISTVER).zip
	zip $(DISTNAME)-$(DISTVER).zip index.cgi *.txt *.css *.js *.dtd *.png *.pwd Makefile

distsource: clean_backup $(wildcard */*.ddoc */*.d */*/*.d */*/*/*.d) index.sh Makefile $(wildcard *.css *.txt *.js *.dtd *.pwd *.svg)
	rm -f $(DISTNAME)-$(DISTVER)-source.zip
	zip $(DISTNAME)-$(DISTVER)-source.zip $+

install:
	mkdir --mode=777 -p $(INSTALLDIR)
	cp -r index.cgi *.txt *.css *.js *.dtd *.png *.pwd $(INSTALLDIR)
	chmod o+x $(INSTALLDIR)/index.cgi
	chmod og+rw $(INSTALLDIR)/admin.pwd
#cgi有効化
	echo AddHandler cgi-script .cgi > /etc/apache2/sites-available/$(PREFIX)
	echo \<Directory $(INSTALLDIR)\> >> /etc/apache2/sites-available/$(PREFIX)
	echo Options +ExecCGI >> /etc/apache2/sites-available/$(PREFIX)
	echo \</Directory\> >> /etc/apache2/sites-available/$(PREFIX)
	chmod 755 /etc/apache2/sites-available/$(PREFIX)
	ln -sf /etc/apache2/sites-available/$(PREFIX) /etc/apache2/sites-enabled/000-$(PREFIX)
#	/etc/init.d/apache2 reload

uninstall:
	rm -rf $(addprefix $(INSTALLDIR)/,index.cgi *.txt *.css *.js *.dtd) /etc/apache2/sites-available/$(PREFIX) /etc/apache2/sites-enabled/000-$(PREFIX)
